package com.xixilala.video.views

import android.annotation.SuppressLint
import android.content.Context
import android.graphics.Bitmap
import android.graphics.Canvas
import android.graphics.Paint
import android.util.AttributeSet
import android.view.View
import com.xixilala.video.util.ImageUtil
import java.lang.ref.WeakReference

class LoadImageView : View {

    private var weakBitmap: WeakReference<Bitmap>? = null //内存不足时回收
//    private val bitmapOptions by lazy {
//        BitmapFactory.Options()
//    }
//    private var imageOrdinaryWidth = 0
//    private var imageOrdinaryHeight = 0

    private val paint by lazy {
        Paint()
    }

    constructor(context: Context?) : this(context, null)
    constructor(context: Context?, attrs: AttributeSet?) : super(context, attrs)

    @SuppressLint("DrawAllocation")
    override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec)

        if (weakBitmap == null) {

            /*val open = context.assets.open("image.png")
            val rect = Rect()
            BitmapFactory.decodeStream(open, rect, bitmapOptions.apply {
                inJustDecodeBounds = true // ==true bm返回空，宽高会放在 Options中
            })

            imageOrdinaryWidth = bitmapOptions.outWidth
            imageOrdinaryHeight = bitmapOptions.outHeight

            val rate = if (imageOrdinaryWidth>measuredWidth) {
                if(imageOrdinaryHeight>measuredHeight) {
                    max(imageOrdinaryHeight / measuredHeight, imageOrdinaryWidth / measuredWidth)
                } else {
                    imageOrdinaryWidth / measuredWidth
                }
            } else {
                if(imageOrdinaryHeight>measuredHeight) {
                    imageOrdinaryHeight / measuredHeight
                } else {
                    1
                }
            }

            open.reset()
            val bmReal = BitmapFactory.decodeStream(open, rect, bitmapOptions.apply {
                inJustDecodeBounds = false
                inSampleSize = rate
            })*/

//            weakBitmap = WeakReference(ImageUtil.getAdaptedBitmap(context, measuredWidth, measuredHeight))
        }
    }

    override fun onDraw(canvas: Canvas?) {
        super.onDraw(canvas)


        canvas?.let { canvas1 ->
            weakBitmap?.get()?.let {
                canvas1.drawBitmap(it, 0f, 0f, paint) //todo 居中
            }
        }
    }
}